﻿

using IdentityModel;
using IdentityServer4.EntityFramework.DbContexts;
using IdentityServer4.EntityFramework.Mappers;
using IdentityServer4.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Permission.Abstract;
using System.Security.Claims;

namespace IdentityServer
{
    public class IdentityServerDataSeed
    {


        //private readonly UserManager<AbpUsers> _userManager;
        //public IdentityServerDataSeed(UserManager<AbpUsers> userManager)
        //{
        //    _userManager = userManager;
        //}

        /// <summary>
        /// 初始化授权种子数据
        /// </summary>
        /// <param name="app"></param>
        public static async void InitializeDatabase(IApplicationBuilder app)
        {


            using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>()?.CreateScope())
            {
                serviceScope?.ServiceProvider.GetRequiredService<PersistedGrantDbContext>().Database.Migrate();

                var context = serviceScope?.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
                context?.Database.Migrate();
                if (!context.Clients.Any())
                {
                    foreach (var client in Config.Clients())
                    {
                        context.Clients.Add(client.ToEntity());
                    }
                    context.SaveChanges();
                }


                if (!context.ApiResources.Any())
                {
                    foreach (var re in Config.ApiResources())
                    {
                        context.ApiResources.Add(re.ToEntity());
                    }
                    context.SaveChanges();
                }

                if (!context.IdentityResources.Any())
                {
                    foreach (var resource in Config.IdentityResources())
                    {
                        context.IdentityResources.Add(resource.ToEntity());
                    }
                    context.SaveChanges();
                }

                if (!context.ApiScopes.Any())
                {
                    foreach (var resource in Config.ApiScopes())
                    {
                        context.ApiScopes.Add(resource.ToEntity());
                    }
                    context.SaveChanges();
                }

                var userDbContext = serviceScope.ServiceProvider.GetRequiredService<IdentityUserDbContext>();
                userDbContext.Database.Migrate();
                IdentityRole? role = null;
                if (!userDbContext.Roles.Any())
                {
                    role = new IdentityRole()
                    {
                        Name = "admin",
                        NormalizedName = "admin"
                    };
                    userDbContext.Roles.Add(role);
      
                    var role2 = new IdentityRole()
                    {
                        Name = "测试角色",
                        NormalizedName = "测试角色"
                    };
                    userDbContext.Roles.Add(role2);

                }
                else
                    role = userDbContext.Roles.Where(r => r.Name.Equals("admin")).FirstOrDefault();


                if (!userDbContext.Users.Any())
                {
                    var user = new AbpUsers()
                    {
                        EmailConfirmed = true,
                        PhoneNumber = "15220231801",
                        PhoneNumberConfirmed = true,

                        UserName = "administrator",
                        PasswordHash = "admin123456",//.Sha256(),
                        Email = "919683350@qq.com",
                        NormalizedUserName = "admin"
                    };
                    //userDbContext.UserClaims.Add(new IdentityUserClaim<string>()
                    //{
                    //    ClaimType = ClaimTypes.Country,
                    //    ClaimValue = "中国",
                    //    UserId = user.Id
                    //});
                    var userManager = serviceScope.ServiceProvider.GetRequiredService<UserManager<AbpUsers>>();
                    //  userDbContext.Set<AbpUsers>().Add(user);
                    // _userManager.CreateAsync(user);
                    var indentityResult = await userManager.CreateAsync(user, "123456");
                    if (indentityResult.Succeeded)
                    {
                        await userManager.AddClaimsAsync(user, new Claim[]
                        {
                            new Claim(JwtClaimTypes.Name, "administrator"),
                            new Claim(JwtClaimTypes.GivenName, "administrator"),
                            new Claim(JwtClaimTypes.FamilyName, "administrator"),
                            new Claim(JwtClaimTypes.WebSite, "http://baidu.com"),
                        });
                        if (role != null)
                        {
                            await userManager.AddToRoleAsync(user, role.Name);
                            //userDbContext.UserRoles.Add(new IdentityUserRole<string>()
                            //{
                            //    RoleId = role.Id,
                            //    UserId = user.Id
                            //});
                        }
                    }

                }
                userDbContext.SaveChanges();
            }



        }

        /// <summary>
        /// 初始化权限种子数据
        /// </summary>
        /// <param name="app"></param>
        public static async void InitializePermissionDatabase(IApplicationBuilder app)
        {
            var permissionDefinitionService = app.ApplicationServices.GetService<IPermissionDefinitionContext>();

            var permissionDefinitionProviderService = app.ApplicationServices.GetService<IPermissionDefinitionProvider>();

            permissionDefinitionProviderService?.Define(permissionDefinitionService);


            var dbContextScope = app.ApplicationServices.CreateScope();
            var dbContext = new AbpDbContext();// dbContextScope.ServiceProvider.GetRequiredService<AbpDbContext>();

            string creatTableSql = @"if not exists(select top 1 * from sysObjects where Id=OBJECT_ID(N'AbpPermissionGrant') and xtype='U')
                                         create table AbpPermissionGrant(
                                          Id uniqueidentifier not null primary key default newid(),
                                          TenantId uniqueidentifier null default null,
                                          Name nvarchar(100) not null default '',
                                          ProviderName nvarchar(5) not null default 'R',
                                          ProviderKey nvarchar(20) not null default 'admin'
                                        );
                                          INSERT INTO AbpPermissionGrant VALUES ( newid(), NULL, N'Order', N'R', N'admin' )";

            dbContext.Database.ExecuteSqlRaw(creatTableSql);



            var list = await dbContext.AbpPermissionGrant.ToListAsync();
            dbContext.Set<AbpPermissionGrant>().RemoveRange(list);

            var group = permissionDefinitionService?.GetGroup();

            //            var testList = dbContext.Set<AbpPermissionGrants>().FromSqlRaw($@"
            //with sql1 as (select* from AbpPermissionGrants)
            //select* from sql1").ToList();

            //var per = new AbpPermissionGrants() { Name = group.Name, ProviderKey = "admin" };
            //dbContext.Set<AbpPermissionGrants>().Add(per);
            //await dbContext.SaveChangesAsync();

            if (group?.Permissions?.Count > 0)
            {
                foreach (var item in group.Permissions)
                {
                    dbContext.Set<AbpPermissionGrant>().Add(new AbpPermissionGrant() { Name = item.Name ?? "-", ProviderKey = "admin" });
                }
                await dbContext.SaveChangesAsync();
            }
        }
    }
}
